package com.yulinlin.admin.modules.im.service.impl;

import com.yulinlin.admin.modules.im.dao.ImMessageDao;
import com.yulinlin.admin.modules.im.domain.ImMessageEntity;
import com.yulinlin.admin.modules.im.domain.ImMessageReceiptEntity;
import com.yulinlin.admin.modules.im.domain.ImSessionUserEntity;
import com.yulinlin.admin.modules.im.domain.enums.ImMessageReceiptEnums;
import com.yulinlin.admin.modules.im.service.IImMessageService;
import com.yulinlin.common.model.ModelSelectWrapper;
import com.yulinlin.common.model.ModelUpdateWrapper;
import com.yulinlin.common.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service

public class ImMessageServiceImpl extends ServiceImpl<ImMessageEntity> implements IImMessageService  {


    @Autowired
    private ImMessageDao dao;

    @Override
    public int readMessage(String imMessageId, String imSessionUserId) {
        ModelUpdateWrapper wrapper =   ModelUpdateWrapper.newWrapper(ImMessageReceiptEntity.class);
        wrapper .eq("imMessageId",imMessageId);
        wrapper.eq("imSessionUserId",imSessionUserId);


        ;

        return 0;
    }

    @Override
    public List<ImMessageEntity> myMeesageList(String imSessionId, String imSessionUserId) {

       List<ImMessageReceiptEntity> entityList = ModelSelectWrapper.newInstance(ImMessageReceiptEntity.class)
                .eq("imSessionUserId",imSessionUserId)
                .eq("imSessionId",imSessionId)
                .selectList();

       if(entityList.isEmpty()){
           return new ArrayList<>();
       }

        Collection ids =  new ArrayList<>();
        for (ImMessageReceiptEntity entity : entityList) {
            ids.add(entity.getImMessageId());

        }
        ImMessageEntity imMessageEntity = new ImMessageEntity();
        List<ImMessageEntity> list =  ModelSelectWrapper.newInstance(ImMessageEntity.class).in("id",ids).selectList();
        return list;
    }

    @Override
    public int sendMessage(ImMessageEntity message) {

        /**
         * 保存消息数据库
         * 群里所有用户都要收到消息回执
         */
        message.createInsertWrapper().execute();
       List<ImSessionUserEntity> sessionUserEntityList= ModelSelectWrapper.newInstance(ImSessionUserEntity.class)
                .eq("imSessionId",message.getImSessionId())
        .selectList();

        for (ImSessionUserEntity entity : sessionUserEntityList) {
            ImMessageReceiptEntity entity1 = new ImMessageReceiptEntity();
            entity1.setUserId(entity.getUserId());
            entity1.setImMessageId(message.getId());

            entity1.setImSessionId(message.getImSessionId());
            entity1.setStatus(ImMessageReceiptEnums.status.unread);
            entity1.createInsertWrapper().execute();
        }
        return 0;
    }
}
